package com.zhs.elasticsearch.config;

import com.zhs.elasticsearch.properties.EsConnectProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhenghuisheng
 * @date 2024/12/15 8:00
 */
@Configuration
@Slf4j
public class ElasticSearchConfig {

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    private final EsConnectProperties esConnectProperties;

    public ElasticSearchConfig(EsConnectProperties esConnectProperties) {
        this.esConnectProperties = esConnectProperties;
    }


    @Bean
    public RestHighLevelClient esRestClient() {
        log.info("ES配置注入完成：,{},{}", esConnectProperties.getHostname(), esConnectProperties.getPort());
        //初始化配置
        RestClientBuilder builder = RestClient.builder(new HttpHost(esConnectProperties.getHostname(), esConnectProperties.getPort()));
        builder.setRequestConfigCallback(requestConfigBuilder ->
                requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000));
        builder.setHttpClientConfigCallback(httpClientBuilder ->
                httpClientBuilder.setMaxConnTotal(100).setMaxConnPerRoute(20));
        return new RestHighLevelClient(builder);
    }
}
